# -*- coding:utf-8 -*-
import base64
import json
import uuid

from util.kafka_producer_connect import KafkaProducerConnect
from util.response_format import ResponseFormat
# 连接对象放在函数外部，定义为全局变量，可以减少连接实例的创建销毁带来的性能浪费
# 消息队列生产者
PRODUCER = KafkaProducerConnect()


def handler(event, context):
    logger = context.getLogger()
    params = json.loads(base64.b64decode(event["body"]).decode().replace("'", '"'))
    user_name = params.get("userName", None)
    verify_type = params.get("verifyType", None)
    contact = params.get("contact", None)
    # 认证ID
    verify_id = str(uuid.uuid4())
    # 根据相应类型发送至相应通道
    type_topic_name = f"{verify_type}_topic"
    # 消息发送
    msg = {"userName": user_name, "verifyId": verify_id, "contact": contact}
    try:
        PRODUCER.send_msg(type_topic_name, msg)
    except ConnectionError:
        logger.error("kafka连接错误，请检查kafka配置信息")
        return ResponseFormat({"code": 500, "msg": "服务器错误"}, 500).to_json()
    return ResponseFormat({"code": 200, "msg": "成功", "verifyId": verify_id}, 200).to_json()